// mircoApp/competitionApply/applyForm/applyForm.js
const app = getApp();
const skinBehavior = require("../../../utils/themeSkin/skinBehavior");
import Dialog from "../../../dist/dialog/dialog";
Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    applyForm:{
      goods_id:'',
      student_id:'',
      mobile:'',
      work_name:'',
      work_url:'',
      teacher_name:'',
      teacher_mobile:'',
      group_name:'',
      code:'',
      unit:''
    },
    studentName:'',
    btnStatus:0,
    selectImgIndex:0,
    fileList4:[],
    stopButton: false,
    iPnoneBottomBol: false, //是否是苹果手机
    sexShow:false,
    studentShow:false,
    radio:'1',
    applyTitle:'选择参赛学员',
    relationArr:[],
    studentArr:[],
    groupArr:[],
    studentIndex:0,
    groupIndex:0,
    applyType:'',
    relationName:'',
    //验证码
    codeText:"获取验证码",
    isDisable:false,
    timer:null,
    uploadUrl:'upload.uploadPic', //上传图片
    fileType:'',
    title:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.goodsId) {
      this.setData({
        'applyForm.goods_id':options.goodsId,
        title:options.title,
      })
    }
    this.initData(); //取消图片和修改图片会触发onshow
    this.getiPnoneBottom();
    this.groupData();
    
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      studentShow:false
    });
    this.studentList();
  },
  initData(){
    this.setData({
      'applyForm.student_id':'',
      'applyForm.mobile':'',
      studentName:'',
      'applyForm.work_name':'',
      'applyForm.work_url':'',
      'applyForm.teacher_name':'',
      'applyForm.teacher_mobile':'',
      'applyForm.group_name':'',
      'applyForm.code':'',
      'applyForm.unit':''
    })
  },
  studentTo() {
    wx.navigateTo({
      url:'/mircoApp/competitionApply/actionStudent/actionStudent'
    })
    //mircoApp/competitionApply/applyForm/applyForm
  },
  getiPnoneBottom() {
    let that = this;
    try {
      let value = wx.getStorageSync('iPhoneBottom');
      if (value) {
        that.setData({
          iPnoneBottomBol: true
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  modelInput(event) {
    const item = event.currentTarget.dataset.item,
          itemValue = event.detail.value;
    this.setData({
      [item]:itemValue
    })
  },
  //学员搜索功能
  onChange(e) {
    this.setData({
      relationName: e.detail,
    });
  },
  onSearch(event) {
    this.setData({
      studentArr:[]
    })
    this.studentList('search')
  },
  studentClose() {
    this.setData({
      studentShow:false
    })
  },
  studentPopOn(event) {
    let {name,type} = event.currentTarget.dataset;
    if(type == 'student') {
      this.data.applyTitle = '选择参赛学员';
      this.data.studentArr = this.data.relationArr;
    } else {
      this.data.applyTitle = '选择参赛组别';
      console.log(this.data.groupArr);
      this.data.studentArr = this.data.groupArr; 
    }
    this.setData( {
      applyTitle:name,
      applyType:type,
      studentArr:this.data.studentArr,
      studentShow:true
    })
  },
  verificationOn() {
    if (app._isTextEmpty(this.data.applyForm.mobile)) {
      app.tips('请填写手机号');
      return;
    }
    let urlStr = app.getNetAddresss("plugin.event-registration.api.goods.goods.send-mobile-code");
    app._getNetWork({
      url: urlStr,
      data: {mobile:this.data.applyForm.mobile},
      success: (resdata) => {
        var res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          this.timeReduce();
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  applyAffirm() {
    if (app._isTextEmpty(this.data.applyForm.student_id)) {
      app.tips('请选择参赛学员');
      return;
    }
    if (app._isTextEmpty(this.data.applyForm.mobile)) {
      app.tips('请填写手机号码');
      return;
    }
    if (app._isTextEmpty(this.data.applyForm.work_name)) {
      app.tips('请填写参赛作品名称');
      return;
    }
    if (app._isTextEmpty(this.data.applyForm.group_name)) {
      app.tips('请选择参赛组别');
      return;
    }
    if (app._isTextEmpty(this.data.applyForm.work_url)) {
      app.tips('请上传作品');
      return;
    }
    let urlStr = app.getNetAddresss("plugin.event-registration.api.goods.goods.entry");
    app._postNetWork({
      url: urlStr,
      data: this.data.applyForm,
      success: (resdata) => {
        var res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          wx.navigateTo({
            url: `/packageD/buy/myOrder_v2/myOrder_v2?tag=apply&total=1&optionsId=&goodsId=${this.data.applyForm.goods_id}&applyId=${data.apply_id}`,
          });
        } else {
          Dialog.alert({
            message: `${res.msg}`,
          })
            .then(() => {
              // on confirm
            });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  timeReduce() {
    // 定时器方法
    let _this = this
    let time = 60
    this.data.timer = setInterval(() => {
      time -= 1
      this.setData({
        isDisable:true,
        codeText:`重新发送${time}s`
      })
      if (time <= 0) {
        this.setData({
          isDisable:false,
          codeText:'获取验证码'
        })
        
        clearInterval(_this.data.timer);
      }
    }, 500);
  },
  studentOn(event) {
    let {item,index} = event.currentTarget.dataset;
    console.log( this.data.applyType); 
    if(this.data.applyType == 'student') {
      this.data.applyForm.student_id = item.id;
      this.data.studentName = item.relation_name;
      this.data.studentIndex = index;
    } else {
      this.data.applyForm.group_name = item.group_name;
      this.data.groupIndex = index;
    }
    this.setData({
      applyType:this.data.applyType,
      'applyForm.student_id':this.data.applyForm.student_id,
      'applyForm.group_name':this.data.applyForm.group_name,
      studentName:item.relation_name,
      studentIndex:this.data.studentIndex,
      groupIndex:this.data.groupIndex,
      studentShow:false
    })
  },
  studentList(type) { //参赛学员
    let urlStr = app.getNetAddresss("plugin.event-registration.api.goods.goods.get-student-list");
    app._getNetWork({
      url: urlStr,
      data: {relation_name:this.data.relationName},
      success: (resdata) => {
        var res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          if(type) {
            this.data.studentArr = data;
          }
          this.setData({
            relationArr:data,
            studentArr:this.data.studentArr
          })
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  groupData() { //参赛学员
    let urlStr = app.getNetAddresss("plugin.event-registration.api.goods.goods.get-group");
    app._getNetWork({
      url: urlStr,
      data: {id:this.data.applyForm.goods_id},
      success: (resdata) => {
        var res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          this.setData({
            groupArr:data
          })
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  onRead(event) { //图片上传功能
    let itemName = event.currentTarget.dataset.itemname;
    console.log(event);
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseMedia({
      count: 1,
      // mediaType: ['video'],
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFiles;
        let photourl = tempFilePaths[0].tempFilePath;
       
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: 'file',
          success(resdata) {
            let res = JSON.parse(resdata.data);
            console.log(res);
            if (res.result == 1) {
              let file = that.getFileExtension(photourl); //读取文件的扩展名
              console.log(file);
              that.setData({
                [itemName]: res.data.img_url,
                fileType:file
              });
              console.log(that.data.applyForm);
            } else {
              wx.showToast({
                icon: 'none',
                title: res.msg,
                duration: 1500
              });
            }
          }
        });
      }
    });
  },
  getFileExtension(filename) {
      // 使用正则表达式匹配文件扩展名
      let match = filename.match(/\.([^.]+)$/);
      // 如果匹配到了扩展名，则返回扩展名，否则返回空字符串
      return match ? match[1] : '';
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})